package com.ruoyi.framework.config;

import com.ruoyi.common.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 服务相关配置
 * 
 * @author ruoyi
 */
@Component
public class ServerConfig
{
    @Value("${swagger.hostName}")
    private String hostName;

    @Value("${swagger.port}")
    private String port;

    @Value("${swagger.protocol}")
    private String protocol;

    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     * 
     * @return 服务地址
     */
    public String getUrl()
    {
        //String url = "";
//        if("localhost".equals(hostName)){
//            HttpServletRequest request = ServletUtils.getRequest();
//            url = getDomain(request);
//        }else{
//            url = protocol + "://" + hostName + ":" + port;
//        }
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    /**
     * 获取文件地址 protocol + "://" + hostName + ":" + port
     *
     * @return 服务地址
     */
    public String getFileUrl()
    {
        return protocol + "://" + hostName + ":" + port;
    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
}
